#! /usr/bin/env python
# coding=utf-8
# ******************************************************************************
# Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
# licensed under the Mulan PSL v2.
# You can use this software according to the terms and conditions of the Mulan PSL v2.
# You may obtain a copy of Mulan PSL v2 at:
#     http://license.coscl.org.cn/MulanPSL2
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR
# PURPOSE.
# See the Mulan PSL v2 for more details.
# Author: senlin
# Create: 2020-08-10
# ******************************************************************************/
"""
log module：logger.py
"""

import logging
import os.path

# Define the output format of the handler
FORMATTER = logging.Formatter('[%(asctime)s][%(levelname)s][%(name)s:%(lineno)d|%(funcName)s] %(message)s')
LEVEL = logging.DEBUG
logging.basicConfig(level=logging.INFO,
                    format='[%(asctime)s][%(levelname)s][%(name)s:%(lineno)d|%(funcName)s] %(message)s')


def init(module):
    """
    定义日志模块，日志路径，日志文件名，日志级别等配置
    :param module: 模块名称
    :return: 日志打印实例
    """
    # init logger
    log = logging.getLogger(module)
    return log


def add_file_handler(logger, rpmname, stepname):
    """
    添加文件句柄
    :param logger: 日志打印实例
    :param rpmname: 包名
    :param stepname: 步骤名
    :return: 无
    """
    # 日志路径为/***/src/Logs/rpm包名
    logger.handlers = []
    srcpath = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))  # return current path
    logpath = os.path.join(srcpath, 'Logs/', rpmname)
    if not os.path.exists(logpath):
        os.makedirs(logpath)
    # 日志文件名为执行步骤名称
    logname = logpath + '/' + stepname + '.log'
    # 创建输出流到日志文件
    fh = logging.FileHandler(logname)
    fh.setLevel(LEVEL)
    fh.setFormatter(FORMATTER)
    logger.addHandler(fh)


def init_license_compare_file(file_path):
    """
    初始化license对比结果文件
    Args:
        file_path: license对比结果文件

    Returns: NONE

    """
    with open(file_path, "w+") as f:
        f.write("Package Name | License in SPEC | License in Source | Consistency\n")
        f.write("---------|----------|---------|---------\n")


def record_license_compare_result(file_path, rpm, spec_license, source_license, is_same):
    """
    记录license对比结果
    Args:
        file_path: license对比结果文件
        rpm: rpm包
        spec_license: spec文件中的license
        source_license: 源码包中的license
        is_same: 上面两项是否相同

    Returns:NONE

    """
    with open(file_path, "a+") as f:
        f.write(rpm + "|" + spec_license + "|" + source_license + "|" + is_same + "\n")
